package com.aqgj.Attachment.service;


import com.alibaba.fastjson.JSONObject;
import com.aqgj.Attachment.bean.Attachment;
import com.aqgj.Attachment.dao.AttachmentDao;
import com.aqgj.User.bean.User;
import com.aqgj.util.GenericsUtils;
import com.aqgj.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Date;
import java.util.List;


@Service("Attachment")
public class AttachmentManager {
    @Autowired
    AttachmentDao attachmentDao;

    /**
     * 保存附件.
     * @param attachment 附件.
     * @return
     */
    public String saveAttachment(Attachment attachment){
        this.attachmentDao.save(attachment);
        return attachment.getId();
    }

    /**
     * 保存附件.
     * @param attachment 附件.
     * @return
     */
    public void save(Attachment attachment){
        this.attachmentDao.save(attachment);
    }

    /**
     * 更新附件.
     * @param attachment 附件.
     * @return
     */
    public void update(Attachment attachment){
        this.attachmentDao.update(attachment);
    }



    /**
     * 保存附件.
     * @param attachment 附件
     * @param isSaveDisk  写入服务器本地
     * @return id
     */
    @Transactional
    public String saveAttachment(Attachment attachment, HttpServletRequest request, Boolean isSaveDisk){
        String id=saveAttachment(attachment);
        if (isSaveDisk&&id!=null) {
            //写入服务器upload
            String path = request.getServletContext().getRealPath("/upload/");
            File file1 = new File(path);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            try {
                bis = new BufferedInputStream(new ByteArrayInputStream(attachment.getFileBody()));
                bos = new BufferedOutputStream(new FileOutputStream(path + attachment.getFileName()));
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = bis.read(buffer)) > 0) {
                    bos.write(buffer);
                }
                bos.flush();
                return id;
            } catch (Exception e) {
                e.printStackTrace();
                return id;
            }
        }
        return id;
    }


    public Attachment get(String  attachmentId){
      return  this.attachmentDao.get(attachmentId);
    }

    /**
     * 根据文件路径path查找Attchement.
     * @param path 文件路径存储和id一致.
     * @return Attchement
     */
    public Attachment getAttchementByPath(String  path){
        return  this.attachmentDao.findUniqueBy("id",path);
    }

    /**
     * 删除附件.
     * @param attachment 附件.
     */
    public void deleteAttachment(Attachment attachment){
        if (attachment == null) {
            return;
        }
        this.attachmentDao.removeById(attachment.getId());
    }

    /**
     * 根据业务Id获取附件.
     * @param businessId 业务id
     * @return
     */
    @Transactional
    public List<Attachment> getAttachmentByBusinessId(String businessId) {
        if(GenericsUtils.isEmpty(businessId)){
            return null;
        }
        return this.attachmentDao.findBy("businessId",businessId);
    }

    /**
     * 保存文件.
     * @param attachment 实体文件
     * @param inputStream 输入流
     */
    public void saveAttachToDB(Attachment attachment, InputStream inputStream){
        attachmentDao.saveAttachToDB(attachment,inputStream);
    }

    /**
     * 解码base64图片
      * @param imgString  base64图片字符串
     * @return
     */
    public  byte[]  decoderBase64(String imgString){
        BASE64Decoder decoder = new BASE64Decoder();
        // Base64解码
        byte[] imageByte = null;
        try {
            imageByte = decoder.decodeBuffer(imgString);
            for (int i = 0; i < imageByte.length; ++i) {
                if (imageByte[i] < 0) {// 调整异常数据
                    imageByte[i] += 256;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageByte;
    }

    /**
     * 保存业务图片
     * @param json   JSONObject（base64加密转换）
     * @param workItem   业务名字
     * @param currUser   当前操作用户
     * @param businessId  业务id
     * @param remark    图片说明
     * @param request
     */
    public void saveAttachment(JSONObject json, String workItem, User currUser, String businessId, HttpServletRequest request,String remark){
        String imgBase64= (String)json.get(workItem);
        String[] imgs=imgBase64.split("\\,");
        Attachment attachment = new Attachment();
        attachment.setWorkItem(workItem);
        attachment.setUploadTime(new Date());
        attachment.setUploaderName(remark);
        attachment.setUploader(currUser.getId());
        attachment.setBusinessId(businessId);
        // 通过base64来转化图片
        attachment.setFileType(imgs[0].split(":")[1].split(";")[0]);
        attachment.setFileName(imgs[2]);
        markImgByText(imgs[1], attachment,"An168");
        String attachmentId = saveAttachment(attachment, request, true);
        attachment.setFilePath(attachmentId);
        save(attachment);
    }



    /**
     * 图片添加文字水印
     * @param img   base64图片
     * @param attachment 图片实体
     * @param logoText  水印文字
     */
    public void markImgByText(String img, Attachment attachment,String logoText) {
        InputStream rfile = new ByteArrayInputStream(decoderBase64(img));
        try {
            rfile = ImageUtil.markImageByText(logoText, rfile, -45);
            byte[] data = new byte[rfile.available()];
            rfile.read(data);
            attachment.setFileBody(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存业务图片
     * @param json  base64加密字符串
     * @param workItem   业务名字
     * @param currUser   当前操作用户
     * @param businessId  业务id
     * @param remark    图片说明
     * @param request
     */
    public void saveAttachment(String json, String workItem, User currUser, String businessId, HttpServletRequest request,String remark){
        String[] imgs=json.split("\\,");
        Attachment attachment = new Attachment();
        attachment.setWorkItem(workItem);
        attachment.setUploadTime(new Date());
        attachment.setUploaderName(remark);
        attachment.setUploader(currUser!=null?currUser.getId():remark);
        attachment.setBusinessId(businessId);
        // 通过base64来转化图片
        attachment.setFileType(imgs[0].split(":")[1].split(";")[0]);
        attachment.setFileName(imgs[2]);
        markImgByText(imgs[1], attachment,"An168");
        String attachmentId = saveAttachment(attachment, request, true);
        attachment.setFilePath(attachmentId);
        save(attachment);
    }
    public  void delete(String id){
        attachmentDao.removeById(id);
    }
}
